package cn.acac.yygh.hosp.service.impl;

import cn.acac.yygh.exception.MyException;
import cn.acac.yygh.hosp.config.ScheduleRepository;
import cn.acac.yygh.hosp.service.DepartmentService;
import cn.acac.yygh.hosp.service.HospitalService;
import cn.acac.yygh.hosp.service.ScheduleService;
import cn.acac.yygh.model.hosp.BookingRule;
import cn.acac.yygh.model.hosp.Department;
import cn.acac.yygh.model.hosp.Hospital;
import cn.acac.yygh.model.hosp.Schedule;
import cn.acac.yygh.vo.hosp.BookingScheduleRuleVo;
import cn.acac.yygh.vo.hosp.ScheduleOrderVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;


    /**
     * 保存第三方医院的信息
     * @param switchMap
     */
    @Override
    public void saveAndUpdate(Map<String, Object> switchMap) {
        // 取出第三方医院的基本信息
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(switchMap), Schedule.class);
        // 根据医院信息、科室信息、排班信息查询MongoDB是否有此信息
        Schedule schedule1 = scheduleRepository.findByHoscodeAndDepcodeAndHosScheduleId(schedule.getHoscode(),schedule.getDepcode(),schedule.getHosScheduleId());
        // 判断是否有信息
        if (schedule1 == null){
            // 进行添加操作
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }else {
            // 进行更新操作
            // 进行添加操作
            schedule.setCreateTime(schedule1.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(schedule1.getIsDeleted());
            schedule.setStatus(schedule1.getStatus());
            scheduleRepository.save(schedule);
        }
    }

    /**
     * 分页信息查询并返回
     * @param switchMap
     * @return
     */
    @Override
    public Page<Schedule> listPage(Map<String, Object> switchMap) {
        // 取出第三方医院的基本信息
        String hoscode = (String) switchMap.get("hoscode");
        Integer pageNum = Integer.parseInt((String) switchMap.get("page"));
        Integer pageSize = Integer.parseInt((String) switchMap.get("limit"));
        // 创建分页对象
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize,Sort.by(Sort.Direction.DESC,"createTime"));
        // 设置查询条件
        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        Example<Schedule> of = Example.of(schedule);
        // 查询信息
        Page<Schedule> schedulePage = scheduleRepository.findAll(of, pageable);
        return schedulePage;
    }

    /**
     * 根据id删除排班信息
     * @param switchMap
     * @return
     */
    @Override
    public void remove(Map<String, Object> switchMap) {
        // 取出删除的条件
        String hoscode = (String) switchMap.get("hoscode");
        String hosScheduleId = (String) switchMap.get("hosScheduleId");

        // 进行删除操作
        Schedule schedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode,hosScheduleId);
        if(schedule == null){
            throw new MyException(5000,"没有该排班信息，请确认无误后在操作！");
        }
        scheduleRepository.deleteById(schedule.getId());
    }

    /**
     * 根据医院科室的信息查询排班信息
     * @param pageNum
     * @param pageSize
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> schedulePage(Integer pageNum, Integer pageSize, String hoscode, String depcode) {
        // 创建存储信息的map
        Map<String,Object> scheduleMap = new HashMap<>();

        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        // 创建查询条件
        Aggregation aggregation1 = Aggregation.newAggregation(
            Aggregation.match(criteria),// 查询条件
            Aggregation.group("workDate")
                    .first("workDate")
                    .as("workDate")
                    .count()
                    .as("docCount")
                    .sum("reservedNumber")
                    .as("reservedNumber")
                    .sum("availableNumber")
                    .as("availableNumber"),// 分组
            Aggregation.sort(Sort.Direction.ASC,"workDate"),    // 根据日期排序
            // 分页
            Aggregation.skip((pageNum - 1) * pageSize),
            Aggregation.limit(pageSize)
        );

        // 使用MongoTemplate进行分组查询
        AggregationResults<BookingScheduleRuleVo> aggregate1 = mongoTemplate.aggregate(aggregation1, Schedule.class, BookingScheduleRuleVo.class);
        // 获取查询结果
        List<BookingScheduleRuleVo> mappedResults = aggregate1.getMappedResults();
        // 设置周几
        for (BookingScheduleRuleVo bookingScheduleRuleVo : mappedResults) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        // 获取总条数
        // 创建查询条件
        Aggregation aggregation2 = Aggregation.newAggregation(
                Aggregation.match(criteria),// 查询条件
                Aggregation.group("workDate")
        );

        // 查询医院名称
        Hospital hospitalByHoscode = hospitalService.findHospitalByHoscode(hoscode,null);

        // 使用MongoTemplate进行分组查询
        AggregationResults<BookingScheduleRuleVo> aggregate2 = mongoTemplate.aggregate(aggregation2, Schedule.class, BookingScheduleRuleVo.class);
        scheduleMap.put("list",mappedResults);
        scheduleMap.put("total",aggregate2.getMappedResults().size());
        scheduleMap.put("hospitalName",hospitalByHoscode.getHosname());
        return scheduleMap;
    }

    /**
     * 根据医院、科室、日期查询当日的医师
     * @param hoscode
     * @param depcode
     * @param date
     * @return
     */
    @Override
    public List<Schedule> dateil(String hoscode, String depcode, String date) {
        // 根据医院编号、科室编号、日期查询医师信息
        // 因为MongoDB严格区分数据类型，我们这里要将workDate转换为日期类型
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(date).toDate());
        scheduleList.stream().forEach(item -> {
            this.packageSchedule(item);
        });
        return scheduleList;
    }

    /**
     * 获取该医院该科室下的排班信息
     * @param hospcode
     * @param deptcode
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Map<String, Object> selectBookingSchedule(String hospcode,
                                                     String deptcode,
                                                     Integer pageNum,
                                                     Integer pageSize) {
        Map<String,Object> result = new HashMap<>();
        // 查询该医院是否存在，并获取该医院的排班规则
        Hospital hospital = hospitalService.findHospByHoscode(hospcode);
        if(hospital == null){
            throw new MyException(50000,"该医院不存在！");
        }
        // 获取该医院的排班规则
        BookingRule bookingRule = hospital.getBookingRule();
        // 获取可以预约的排班数据
        IPage<Date> iPage = this.getListDate(pageNum,pageSize,bookingRule);
        // 获取当前页可预约的日期
        List<Date> records = iPage.getRecords();
        // 获取可预约日期科室的剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hospcode).and("depcode").is(deptcode).and("workDate").in(records);
        Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
                Aggregation.group("workDate")
                .first("workDate").as("workDate")
                .sum("availableNumber").as("availableNumber")
                .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();
        // 获取科室剩余预约数
        // 合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date,BookingScheduleRuleVo> scheduleRuleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(mappedResults)){
            // 转换为map
            scheduleRuleVoMap  = mappedResults.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i=0, len=records.size(); i<len; i++) {
            Date date = records.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleRuleVoMap.get(date);
            if(null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && pageNum == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && pageNum == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.findHospByHoscode(hospcode.toString()).getHosname());
        //科室
        Department department =departmentService.getDepartment(hospcode, deptcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 根据排班id查询排班医生信息
     * @param id
     * @return
     */
    @Override
    public Schedule findScheduleById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        this.packageSchedule(schedule);
        return schedule;
    }

    /**
     * 根据scheduleId查询scheduleOrderVo信息
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo findScheduleOrderById(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        // 设置相关信息
        BeanUtils.copyProperties(schedule,scheduleOrderVo);
        Hospital hospital = hospitalService.findHospByHoscode(schedule.getHoscode());
        // 根据医院编号查询医院名称
        scheduleOrderVo.setHosname(hospital.getHosname());
        // 根据医院编号和科室编号查询科室名称
        scheduleOrderVo.setDepname(departmentService.findDeptNameByHoscodeAngDeptcode(schedule.getHoscode(),schedule.getDepcode()));
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        // 设置退号时间
        DateTime dateTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(hospital.getBookingRule().getQuitDay()).toDate(), hospital.getBookingRule().getQuitTime());
        // 设置当天的停止预约的挂号时间
        Date workDate = schedule.getWorkDate();
        // 获取当前医院的停止挂号时间
        String stopTime = hospital.getBookingRule().getStopTime();
        DateTime dateTime1 = this.getDateTime(workDate, stopTime);
        scheduleOrderVo.setStopTime(dateTime1.toDate());
        scheduleOrderVo.setQuitTime(dateTime.toDate());
        return scheduleOrderVo;
    }

    /**
     * 根据id更新排班信息
     * @param scheduleId
     * @param availableNumber
     * @return
     */
    @Override
    public boolean updateScheduleById(String scheduleId, Integer availableNumber) {
        // 根据id查询排班信息
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        schedule.setAvailableNumber(availableNumber);
        schedule.setUpdateTime(new Date());
        // 保存排班信息
        scheduleRepository.save(schedule);
        return true;
    }

    /**
     * 更新医生的预约数量
     * @param scheduleId
     * @return
     */
    @Override
    public Boolean cancelSchedule(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        schedule.setAvailableNumber(schedule.getAvailableNumber() + 1);
        scheduleRepository.save(schedule);
        return true;
    }

    /**
     * 获取该医院可以预约排班的数据
     * @param pageNum
     * @param pageSize
     * @param bookingRule
     * @return
     */
    private IPage getListDate(Integer pageNum, Integer pageSize, BookingRule bookingRule) {
        // 获取每天放号的时间
        DateTime dateTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        // 预约周期
        Integer cycle = bookingRule.getCycle();
        // 如果当天放号的时间已过，预约周期加一
        if(dateTime.isBeforeNow()){
            cycle += 1;
        }
        // 可预约的所有排班日期
        List<Date> dateList = new ArrayList<>();    // 放的就是该医院下可预约的时间
        for (Integer i = 0; i < cycle; i++) {
            dateList.add(new DateTime(new DateTime().plusDays(i).toString("yyyy-MM-dd")).toDate());
        }
        // 日期分页，日期显示不一样，多了就需要进行分页
        List<Date> pageDateList = new ArrayList<>();
        Integer start = (pageNum - 1) * pageSize;
        Integer end = start + pageSize;
        // 判断end是否大于医院总排班天数
        if(end > dateList.size()){
            end = dateList.size();
        }
        for (Integer i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date> datePage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize, dateList.size());
        // 将这一页的数据放入分页对象中
        datePage.setRecords(pageDateList);
        return datePage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }
    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.findHospitalByHoscode(schedule.getHoscode(),null).getHosname());
        //设置科室名称
        schedule.getParam().put("depname",
                departmentService.findDeptNameByHoscodeAngDeptcode(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
